package uestc.lj.gulishop.seckill.scheduled;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import uestc.lj.gulishop.seckill.service.SeckillService;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品的定时上架
 *
 * @Author:Crazlee
 * @Date:2021/6/22
 */
@Service
@Slf4j
public class SeckillSkuScheduled {

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private RedissonClient redissonClient;

    private final String UPLOAD_LOCK = "seckill:upload:lock:";

    /**
     * 每天凌晨3点定时上架最近三天的秒杀商品
     * 保证幂等性处理
     */
    @Scheduled(cron = "*/5 * * * * ?")
    public void uploadSeckillSkuInThreeDays() {
        log.info("秒杀商品上架");
        // 加分布式锁，保证接口幂等性
        RLock lock = redissonClient.getLock(UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            seckillService.uploadSeckillSkuInThreeDays();
        } finally {
            lock.unlock();
        }
    }
}
